package cn.shengchao.controler;

import cn.shengchao.base.event.PaySuccessMessageEvent;
import cn.shengchao.examstar.pay.infrastructure.dao.OrderDao;
import cn.shengchao.examstar.pay.infrastructure.dao.PayOrderItemDao;
import cn.shengchao.examstar.pay.infrastructure.dao.po.PayOrder;
import cn.shengchao.examstar.pay.infrastructure.dao.po.PayOrderItem;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.continew.starter.web.model.R;

import java.util.List;

/**
 * @program: examstarapi
 * @description: 支付成功测试
 * @author: Xiong weiqiang
 * @create: 2025-04-29 15:27
 */


@RestController
@Slf4j
@CrossOrigin("${project.cross-origin}")
@RequestMapping("/api/${project.version}/paySuccessTest")
public class PaySuccessTestController {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private PayOrderItemDao payOrderItemDao;
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    @RequestMapping("{payOrderId}")
    public R<String> paySuccessTest(@PathVariable String payOrderId) {
        PayOrder order = orderDao.selectOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderId, payOrderId));
        List<PayOrderItem> payOrderItems = payOrderItemDao.selectList(new LambdaQueryWrapper<PayOrderItem>()
                .eq(PayOrderItem::getOrderId, payOrderId));

        // 发送MQ消息
        PaySuccessMessageEvent eventMessage = new PaySuccessMessageEvent(PaySuccessMessageEvent.PaySuccessMessage
                .builder()
                .userId(order.getUserId())
                .productType(order.getProductType())
                .productId(order.getProductId())
                .tradeNo(payOrderId)
                .amount(order.getTotalAmount())
                .shareCode(order.getShareCode())
                .subProductIds(payOrderItems.stream().map(PayOrderItem::getProductId).toList())
                .payTime(order.getPayTime())
                .build());
        eventPublisher.publishEvent(eventMessage);
        return R.ok("支付成功测试");
    }

}